package com.talos.ums.service.usercarrier;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.usercarrier.vo.UmsUserCarrierPageReqVO;
import com.talos.ums.controller.admin.usercarrier.vo.UmsUserCarrierSaveReqVO;
import com.talos.ums.dal.dataobject.usercarrier.UmsUserCarrierDO;
import com.talos.ums.dal.mysql.usercarrier.UmsUserCarrierMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户承运商关联表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserCarrierServiceImpl implements UmsUserCarrierService {

    @Resource
    private UmsUserCarrierMapper userCarrierMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserCarrier(UmsUserCarrierSaveReqVO createReqVO) {
        // 插入
        UmsUserCarrierDO userCarrier = BeanUtils.toBean(createReqVO, UmsUserCarrierDO.class);
        userCarrierMapper.insert(userCarrier);
        // 返回
        return userCarrier.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserCarrier(UmsUserCarrierSaveReqVO updateReqVO) {
        // 校验存在
        validateUserCarrierExists(updateReqVO.getId());
        // 更新
        UmsUserCarrierDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserCarrierDO.class);
        userCarrierMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserCarrier(Long id) {
        // 校验存在
        validateUserCarrierExists(id);
        // 删除
        userCarrierMapper.deleteById(id);
    }

    private void validateUserCarrierExists(Long id) {
        if (userCarrierMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserCarrierDO getUserCarrier(Long id) {
        return userCarrierMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserCarrierDO> getUserCarrierPage(UmsUserCarrierPageReqVO pageReqVO) {
        return userCarrierMapper.selectPage(pageReqVO);
    }

}
